<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <!-- <el-input
        v-model="listQuery.userId"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入用户ID"
      />-->
      <el-input
        v-model="listQuery.orderNo"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入订单编号"
      />
      <el-select
        v-model="listQuery.orderStatusIndex"
        style="width: 200px"
        class="filter-item"
        placeholder="请选择订单状态"
      >
        <el-option v-for="(key,value) in statusMap" :key="value" :label="key.name" :value="value" />
      </el-select>
      <el-date-picker
        v-model="listQuery.searchTime"
        class="filter-item block"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="yyyy-MM-dd hh:mm"
        value-format="yyyy-MM-dd hh:mm"
        @change="selectTime"
      />
      <!-- <el-date-picker
        v-model="listQuery.startDate"
        class="filter-item"
        type="datetime"
        placeholder="起始日期"
        value-format="yyyy-MM-dd hh:mm"
        clearable
      />
      <el-date-picker
        v-model="listQuery.endDate"
        class="filter-item"
        type="datetime"
        placeholder="截止日期"
        value-format="yyyy-MM-dd hh:mm"
        clearable
      />-->
      <el-button
        v-permission="['GET /admin/order/list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
      <!-- <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >导出</el-button>-->
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" min-width="100" label="订单编号" prop="orderNo" />
      <el-table-column align="center" label="订单状态" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1">待付款</el-tag>
          <el-tag v-if="scope.row.status === 5 && scope.row.isRefund === 1" type="warning">申请退款</el-tag>
          <el-tag
            v-else-if="scope.row.status === 5 && scope.row.deliveryStatus === 0&&scope.row.isRefund!=4"
            type="info"
          >待发货</el-tag>
          <el-tag
            v-else-if="scope.row.status === 5 && scope.row.deliveryStatus === 1&&scope.row.isRefund!=4"
            type="success"
          >已发货</el-tag>
          <el-tag
            v-if="scope.row.status === 5 &&scope.row.isRefund==4&&scope.row.status!==8"
            type="warning"
          >退款中</el-tag>
          <el-tag v-if="scope.row.status === 6" type="success">交易已完成</el-tag>
          <el-tag v-if="scope.row.status === 7" type="danger">已取消</el-tag>
          <el-tag v-if="scope.row.status === 8" type="success">已退款</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="订单金额" prop="amount" />
      <el-table-column align="center" label="支付金额" prop="actualPrice" />
      <el-table-column align="center" label="支付时间" prop="paymentTime" />
      <el-table-column align="center" label="物流单号" prop="deliverySn" />
      <el-table-column align="center" label="物流渠道" prop="deliveryCompany" />
      <el-table-column align="center" label="操作" width="400" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['GET /admin/order/detail']"
            type="primary"
            size="small"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            v-permission="['GET /admin/order/detail']"
            v-if="scope.row.status === 5 && scope.row.isRefund === 1"
            type="success"
            size="small"
            @click="onPassComment(scope.row)"
          >通过</el-button>
          <el-button
            v-permission="['GET /admin/order/detail']"
            v-if="scope.row.status === 5 && scope.row.isRefund === 1"
            type="danger"
            size="small"
            @click="onRefuseComment(scope.row)"
          >拒绝</el-button>
          <el-button
            v-permission="['GET /admin/order/detail']"
            v-if="scope.row.status === 5 && scope.row.deliveryStatus === 0 && scope.row.isRefund != 4"
            type="danger"
            size="small"
            @click="onShipOrder(scope.row.orderId)"
          >发货</el-button>
          <el-button
            v-permission="['GET /admin/order/detail']"
            v-if="scope.row.status === 5 && scope.row.deliveryStatus === 1&&scope.row.isRefund!=4"
            type="danger"
            size="small"
            @click="getDeliveryOrdersFun(scope.row)"
          >查询物流</el-button>
          <el-button
            v-permission="['GET /admin/order/detail']"
            v-if="scope.row.status === 5 &&scope.row.isRefund ===4"
            type="danger"
            size="small"
            @click="onCompleteOrder(scope.row)"
          >完成退款</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <!-- 订单详情对话框 -->
    <el-dialog :visible.sync="orderDialogVisible" title="订单详情" width="800px">
      <section ref="print">
        <el-form :data="orderDetail" label-position="left">
          <el-form-item label="订单编号">
            <span>{{ orderDetail.orderNo }}</span>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-tag v-if="orderDetail.status === 1">待付款</el-tag>
            <el-tag
              v-if="orderDetail.status === 5 && orderDetail.isRefund === 1"
              type="warning"
            >申请退款</el-tag>
            <el-tag
              v-else-if="orderDetail.status === 5 && orderDetail.deliveryStatus === 0 &&orderDetail.isRefund==0"
              type="info"
            >待发货</el-tag>
            <el-tag
              v-else-if="orderDetail.status === 5 && orderDetail.deliveryStatus === 1 &&orderDetail.isRefund==0"
              type="success"
            >已发货</el-tag>
            <el-tag
              v-else-if="orderDetail.status === 5 && orderDetail.isRefund==4"
              type="success"
            >退款中</el-tag>
            <el-tag v-if="orderDetail.isRefund===3" type="warning">已拒绝</el-tag>
            <el-tag v-if="orderDetail.status===6" type="success">交易已完成</el-tag>
            <el-tag v-if="orderDetail.status===7" type="danger">已取消</el-tag>
            <el-tag v-if="orderDetail.status===8" type="success">已退款</el-tag>
          </el-form-item>
          <el-form-item v-if="orderDetail.address" label="收货信息">
            <div>（收货人）{{ orderDetail.address.name }}</div>
            <div>（手机号）{{ orderDetail.address.phone }}</div>
            <div>（地址）{{ orderDetail.address.province }}{{ orderDetail.address.city }}{{ orderDetail.address.region }}</div>
            <div>（详细地址）{{ orderDetail.address.detailAddress }}</div>
          </el-form-item>
          <el-form-item
            v-if="orderDetail.status === 5 && orderDetail.deliveryStatus === 1"
            label="发货信息"
          >
            <div>（物流渠道）{{ orderDetail.deliveryCompany }}</div>
            <div>（物流单号）{{ orderDetail.deliverySn }}</div>
          </el-form-item>
          <el-form-item v-if="orderDetail.isRefund==3" label="拒绝原因">
            <div>{{ orderDetail.handleNote }}</div>
          </el-form-item>
          <el-form-item label="商品信息">
            <el-table :data="orderDetail.goods" border fit highlight-current-row>
              <el-table-column align="center" label="商品名称" prop="itemName" />
              <el-table-column align="center" label="商品分类" prop="itemTypeName" />
              <el-table-column align="center" label="商品数量" prop="orderNumber" />
              <el-table-column align="center" label="商品单价" prop="originalPrice" />
              <el-table-column align="center" label="商品总金额" prop="amount" />
            </el-table>
          </el-form-item>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">取 消</el-button>
        <!-- <el-button type="primary" @click="printOrder">打 印</el-button> -->
      </span>
    </el-dialog>
    <refuse
      :quality.sync="orderDialogVisible1"
      :refuse-item="refuseItem"
      @onRefuseComment="onRefuseComment1"
    />
    <sendout
      :quality.sync="orderDialogVisible2"
      :order-id="sendorderId"
      @onShipOrder="onShipOrder2"
    />
    <wuliu :wuliu-data="wuliuData" :quality.sync="orderDialogVisible3" />
  </div>
</template>

<script>
import {
  listOrder,
  shipOrder,
  passComment,
  getDeliveryOrders
} from '@/api/order'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import checkPermission from '@/utils/permission' // 权限判断函数
import refuse from './components/refuse'
import sendout from './components/sendout'
import wuliu from './components/wuliu'
export default {
  name: 'Order',
  components: { Pagination, refuse, sendout, wuliu },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        index: 0,
        page: 1,
        size: 10,
        orderNo: '',
        orderStatusIndex: 0,
        startDate: '',
        endDate: '',
        searchTime: []
      },
      orderDialogVisible: false,
      orderDialogVisible1: false,
      orderDialogVisible2: false,
      orderDialogVisible3: false,
      sendorderId: null,
      refuseItem: null, // 拒绝订单
      orderDetail: {},
      wuliuData: null,
      downloadLoading: false,
      statusMap: [
        {
          name: '全部',
          icon: 'daifukuan-02',
          id: 0,
          categoryId: 0,
          status: null
        },
        {
          name: '待付款',
          icon: 'daifukuan-02',
          id: 1,
          categoryId: 1,
          status: 1
        },
        {
          name: '待发货',
          icon: 'daifahuo',
          id: 2,
          categoryId: 2,
          status: 5,
          deliveryStatus: 0
        },
        {
          name: '待收货',
          icon: 'daishouhuo-03',
          id: 3,
          categoryId: 3,
          status: 5,
          deliveryStatus: 1
        },
        {
          name: '申请退款',
          icon: 'tuikuan-04',
          id: 4,
          status: 5,
          isRefund: 1,
          categoryId: 4
        },
        {
          name: '退款中',
          icon: 'tuikuan-04',
          id: 5,
          status: 5,
          isRefund: 4,
          categoryId: 4
        },
        {
          name: '退款完成',
          icon: 'tuikuan-04',
          id: 6,
          status: 8,
          categoryId: 4
        },
        {
          name: '交易完成',
          icon: 'tuikuan-04',
          id: 7,
          status: 6,
          categoryId: 4
        },
        {
          name: '已取消',
          icon: 'tuikuan-04',
          id: 8,
          status: 7,
          categoryId: 4
        }
      ]
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    checkPermission,
    getDeliveryOrdersFun(item) {
      getDeliveryOrders({ orderNo: item.orderNo }).then(res => {
        const steps = res.data.data.result.list
        steps.forEach((item, index) => {
          steps[index][`content`] = item.status
          steps[index][`timestamp`] = item.time
        })
        this.wuliuData = steps
        this.orderDialogVisible3 = true
      })
    },
    getList(e) {
      if (e && e.page) {
        this.listQuery.index = e.page - 1
      }
      this.listLoading = true
      const data = Object.assign({}, this.listQuery)
      const orderStatusIndex = data.orderStatusIndex
      if (orderStatusIndex === 1) {
        data[`status`] = this.statusMap[`${orderStatusIndex}`].status
      } else if (orderStatusIndex === 2 || orderStatusIndex === 3) {
        data[`status`] = this.statusMap[`${orderStatusIndex}`].status
        data[`deliveryStatus`] = this.statusMap[
          `${orderStatusIndex}`
        ].deliveryStatus
        data[`isRefund`] = 0
      } else if (orderStatusIndex === 4 || orderStatusIndex === 5) {
        data[`status`] = this.statusMap[`${orderStatusIndex}`].status
        data[`isRefund`] = this.statusMap[`${orderStatusIndex}`].isRefund
      } else {
        data[`status`] = this.statusMap[`${orderStatusIndex}`].status
      }
      listOrder(data)
        .then(response => {
          this.list = response.data.data.content
          this.total = response.data.data.totalRecords
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDetail(row) {
      const {
        itemName,
        itemType,
        itemTypeName,
        orderNumber,
        originalPrice,
        amount
      } = row
      this.orderDetail = {
        ...row,
        goods: [
          {
            itemName,
            itemType,
            itemTypeName,
            orderNumber,
            originalPrice,
            amount
          }
        ]
      }
      this.orderDialogVisible = true
    },
    onShipOrder(sendorderId) {
      // 发货
      const self = this
      self.orderDialogVisible2 = true
      self.sendorderId = sendorderId
    },
    onShipOrder2(data) {
      shipOrder(data).then(res => {
        this.handleFilter()
      })
    },
    onPassComment(row) {
      const data = {
        id: row.refundId,
        status: 1
      }
      passComment(data).then(res => {
        this.handleFilter()
      })
    },
    onRefuseComment(row) {
      const self = this
      self.orderDialogVisible1 = true
      self.refuseItem = row
    },
    onRefuseComment1(data) {
      // 拒绝回调
      passComment(data).then(res => {
        this.handleFilter()
      })
    },
    onCompleteOrder(row) {
      const data = {
        id: row.refundId,
        status: 2
      }
      passComment(data).then(res => {
        this.handleFilter()
      })
    },
    selectTime(val) {
      if (val) {
        this.listQuery.startDate = val[0]
        this.listQuery.endDate = val[1]
      } else {
        this.listQuery.startDate = ''
        this.listQuery.endDate = ''
      }
    }
    // handleDownload() {
    //   this.downloadLoading = true
    //   import('@/vendor/Export2Excel').then(excel => {
    //     const tHeader = [
    //       '订单ID',
    //       '订单编号',
    //       '用户ID',
    //       '订单状态',
    //       '是否删除',
    //       '收货人',
    //       '收货联系电话',
    //       '收货地址'
    //     ]
    //     const filterVal = [
    //       'id',
    //       'orderSn',
    //       'userId',
    //       'orderStatus',
    //       'isDelete',
    //       'consignee',
    //       'mobile',
    //       'address'
    //     ]
    //     excel.export_json_to_excel2(tHeader, this.list, filterVal, '订单信息')
    //     this.downloadLoading = false
    //   })
    // },
    // printOrder() {
    //   this.$print(this.$refs.print)
    //   this.orderDialogVisible = false
    // }
  }
}
</script>
